# scp(1) completion


comp_include _dequote _expand _get_cword _known_hosts


_scp()
{
    local cur optconfigfile userhost path

    COMPREPLY=()
    cur=`_get_cword ":"`

    _expand || return 0

    if [[ "$cur" == *:* ]]; then
	local IFS=$'\t\n'
        # remove backslash escape from :
        cur=${cur/\\:/:}
        userhost=${cur%%?(\\):*}
        path=${cur#*:}
        # unescape spaces
        path=${path//\\\\\\\\ / }
        if [ -z "$path" ]; then
            # default to home dir of specified user on remote host
            path=$(ssh -o 'Batchmode yes' $userhost pwd 2>/dev/null)
        fi
        # escape spaces; remove executables, aliases, pipes and sockets;
        # add space at end of file names
        COMPREPLY=( $( ssh -o 'Batchmode yes' $userhost \
                   command ls -aF1d "$path*" 2>/dev/null | \
                   sed -e "s/[][(){}<>\",:;^&!$&=?\`|\\ ']/\\\\\\\\\\\\&/g" \
                   -e 's/[*@|=]$//g' -e 's/[^\/]$/& /g' ) )
        return 0
    fi

    # Search COMP_WORDS for '-F configfile' argument
    set -- "${COMP_WORDS[@]}"
    while [ $# -gt 0 ]; do
	if [ "${1:0:2}" = -F ]; then
	    if [ ${#1} -gt 2 ]; then
		optconfigfile="$(_dequote "$1")"
	    else
		shift
		[ "$1" ] && optconfigfile="$(_dequote "-F$1")"
	    fi
	    break
	fi
	shift
    done

    [[ "$cur" == */* ]] || _known_hosts -c -a "$optconfigfile"
	local IFS=$'\t\n'
        COMPREPLY=( "${COMPREPLY[@]}" $( command ls -aF1d $cur* \
                2>/dev/null | sed \
                -e "s/[][(){}<>\",:;^&!$&=?\`|\\ ']/\\\\&/g" \
                -e 's/[*@|=]$//g' -e 's/[^\/]$/& /g' ) )
    return 0
}
